﻿using System.Diagnostics;

namespace XYAC.Framework.WohuaMesExtend.IHI
{
    public sealed class ProcessSingleInstance
    {
        private static Mutex _mutex;
        public const string MutexName = "Global\\WohuaMesExtendAppMutex";
        public const string EventName = "Global\\WohuaMesExtendAppEvent";

        /// <summary>
        /// 通过互斥体以及信号接收事件创建窗体
        /// </summary>
        /// <returns></returns>
        public static bool AlreadyRunning2()
        {
            // 尝试创建互斥体
            _mutex = new Mutex(true, MutexName, out bool createdNew);

            if (createdNew)
            {
                // 第一次运行时创建命名事件
                EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventName);
            }
            else
            {
                // 如果已经有实例在运行，则触发事件
                EventWaitHandle.OpenExisting(EventName).Set();
                return true;
            }

            return false;
        }

        public static void ReleaseMutex()
        {
            _mutex?.ReleaseMutex();
        }


    }

}
